<template>
  <view class="login-container">
    <view class="login-box">
      <!-- 顶部标题 -->
      <view class="login-header">
        <text class="login-title">欢迎登录</text>
      </view>

      <!-- 表单区域 -->
      <view class="login-form">
        <u--form :model="formData" ref="loginForm" :rules="rules" labelPosition="top" labelWidth="auto">
          <!-- 手机号登录表单 -->
          <template v-if="currentType === 0">
            <u-form-item label="手机号" prop="phone">
              <u-input v-model="formData.phone" placeholder="请输入手机号" maxlength="11" type="number"></u-input>
            </u-form-item>
            <u-form-item label="验证码" prop="code">
              <u-input v-model="formData.code" placeholder="请输入验证码" maxlength="4" type="number">
                <template #suffix>
                  <u-code ref="uCode" keepRunning @change="codeChange" seconds="60" changeText="X秒后重新获取" unique-key="page-login"></u-code>
                  <u-button @tap="getCode" :text="tips" type="primary" size="mini"></u-button>
                </template>
              </u-input>
            </u-form-item>
          </template>

          <!-- 账号密码登录表单 -->
          <template v-else>
            <u-form-item label="账号" prop="username">
              <u--input v-model="formData.username" placeholder="请输入账号"></u--input>
            </u-form-item>
            <u-form-item label="密码" prop="password">
              <u--input v-model="formData.password" type="password" placeholder="请输入密码"></u--input>
            </u-form-item>
          </template>
        </u--form>

        <!-- 切换登录方式和忘记密码 -->
        <view class="action-buttons">
          <view class="switch-type" @click="handleTypeChange">
            <text>{{ currentType === 0 ? '账号密码登录' : '验证码登录' }}</text>
          </view>
          <view class="forget-password" @click="handleForgetPassword" v-if="currentType === 1">
            <text>忘记密码？</text>
          </view>
        </view>

        <!-- 登录按钮 -->
        <view class="login-button">
          <u-button type="primary" :disabled="!isFormValid" @click="handleLogin">登录</u-button>
        </view>
        <view class="login-tips">若您未注册,验证后将自动注册并登录</view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      currentType: 0, // 0:手机号验证码登录 1:账号密码登录
      formData: {
        phone: '',
        code: '',
        username: '',
        password: ''
      },
      tips: "",
      rules: {
        phone: [{
          required: true,
          message: '请输入手机号',
          trigger: ['blur', 'change']
        }, {
          pattern: /^1[3-9]\d{9}$/,
          message: '手机号格式不正确',
          trigger: ['blur']
        }],
        code: [{
          required: true,
          message: '请输入验证码',
          trigger: ['blur', 'change']
        }, {
          len: 4,
          message: '验证码长度应为4位',
          trigger: ['blur', 'change']
        }],
        username: [{
          required: true,
          message: '请输入账号',
          trigger: ['blur', 'change']
        }],
        password: [{
          required: true,
          message: '请输入密码',
          trigger: ['blur', 'change']
        }]
      }
    }
  },
  computed: {
    isFormValid() {
      if (this.currentType === 0) {
        return this.formData.phone && this.formData.code
      } else {
        return this.formData.username && this.formData.password
      }
    }
  },
  onReady() {
    this.$refs.loginForm.setRules(this.rules)
  },
  methods: {
    // 切换登录方式
    handleTypeChange() {
      this.currentType = this.currentType === 0 ? 1 : 0
      this.resetForm()
    },
    // 重置表单
    resetForm() {
      this.formData = {
        phone: '',
        code: '',
        username: '',
        password: ''
      }
      this.$refs.loginForm.resetFields()
    },
    // 获取验证码
    codeChange(text) {
      this.tips = text;
    },
    getCode() {
      this.$refs.loginForm.validateField('phone', (errorRules) => {

        if (!errorRules || errorRules.length === 0) {
          if (this.$refs.uCode.canGetCode) {
            this.$utils.showLoading()

            this.$services.loginService.getSmsCode(this.formData.phone, 0).then(res => {
              this.formData.code = res.msgCode || ''
              this.$refs.uCode.start();
              this.$utils.hideLoading()
            }).catch((err) => {
              this.$utils.hideLoading()
            })
          } else {
            this.$utils.showMessage('请稍后再来尝试')
          }

        }
      })

    },
    // 处理登录
    handleLogin() {
      this.$refs.loginForm.validate().then(valid => {
        if (valid) {
          this.$utils.showLoading('登录中...')
          
          // 根据登录类型选择登录方法
          let loginRequest
          if (this.currentType === 0) {
            // 验证码登录
            loginRequest = this.$services.loginService.loginByCode(this.formData.phone, this.formData.code)
          } else {
            // 账号密码登录
            loginRequest = this.$services.loginService.loginByPassword(this.formData.username, this.formData.password)
          }

          // 执行登录流程
          loginRequest
            .then(res => {
              // 先保存token
              return this.$store.dispatch('user/saveToken', res.token || '')
            })
            .then(() => {
              // token保存成功后获取用户信息
              return this.$services.loginService.getUserInfo()
            })
            .then(res => {
              // 保存用户信息
              return this.$store.dispatch('user/setUserInfo', res?.user)
            })
            .then(() => {
              this.$utils.hideLoading()
              // 登录成功后的跳转
              uni.reLaunch({
                url: '/pages/index/index'
              })
            })
            .catch(err => {
              console.error('登录失败:', err)
              this.$utils.hideLoading()
            })
        }
      })
    },
    // 处理忘记密码
    handleForgetPassword() {
      uni.navigateTo({
        url: '/pages/login/resetPwd'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  box-sizing: border-box;
  background-color: #fff;
  padding: 40rpx;

  .login-box {
    border-radius: 20rpx;
    padding: 40rpx;
    margin-top: 100rpx;

    .login-header {
      margin-top: 50rpx;
      text-align: center;
      margin-bottom: 120rpx;

      .login-title {
        font-size: 40rpx;
        font-weight: bold;
        color: #333;
      }
    }

    .login-form {
      .code-input {
        display: flex;
        align-items: center;
        gap: 20rpx;

        :deep(.u-input) {
          flex: 1;
        }

        .u-button {
          width: 200rpx;
          flex-shrink: 0;
        }
      }

      .action-buttons {
        display: flex;
        justify-content: space-between;
        margin: 20rpx 0;

        .switch-type,
        .forget-password {
          text {
            color: #2979ff;
            font-size: 28rpx;
          }
        }
      }

      .login-button {
        margin-top: 60rpx;
      }
      .login-tips {
        margin-top: 20rpx;
        text-align: center;
        font-size: 20rpx;
        color: #666;
      }
    }
  }
}
</style>